import React from 'react';
import fns from '../../store/asyncMethods';
import {connect,Provider} from 'react-redux';
import './Dati.css';
import { Toast, WhiteSpace, WingBlank, Button } from 'antd-mobile';
// 使用redux
  // 将修改store到方法映射到props上，默认会传入store里到dispach里
  function mapDispatchToprops(dispatch) { 
      return {
        getTrafficData:async()=>{
            let list = await fns.Timulist();
            dispatch({type:'getTimu',content:list});
        },
        addSettlementData(data){
            dispatch({type:'addSettlementData',data:data});
        }
      }
   };
  // 将state映射到props上
function mapStateToProps(state){
    return {
      TopicData:state.TimuList 
    }
  }; 
class Dati1 extends React.Component{
    constructor(props){
        super(props);
        this.state={
            countNum:0,
            randomNum:Math.floor(Math.random()*(9+1-0)+0),
            currentTotal:0,
            selectRightNum:0,
            selectWrongNum:0,
            integral:0
        };
        this.resetTopic=this.resetTopic.bind(this);
        };
    componentWillMount(){
        //获取答题数据
         if(!this.props.TopicData){
             console.log('无缓存数据，请求获取');
             this.props.getTrafficData();
         };
    };
    changeTopic(type,timuTotal){
        // console.log('传过来的type是：',type)
        type = Number(type);
        switch (type) {
            case 1:
                console.log('hello1',timuTotal-1,this.state.countNum)
                if(this.state.countNum>=timuTotal-1){
                    Toast.info('没有题目啦！', 1);
                }else{
                    this.setState({
                        countNum:this.state.countNum+1,
                        currentTotal:timuTotal
                    })
                }
                 break;
            case -1:
                console.log('hello2',this.state.countNum)
                if(this.state.countNum<=0){
                    Toast.info('到顶啦！', 1);
                }else{
                    this.setState({
                        countNum:this.state.countNum-1,
                        currentTotal:timuTotal
                    })
                }
                 break;
            default:
                break;
        };
    };
    resetTopic(){
        this.setState({
            randomNum:Math.floor(Math.random()*(9+1-0)+0),
            countNum:0
        });
        let items = document.getElementsByClassName('item');
        for(let i=0;i<items.length;i++){
            items[i].style.backgroundColor='rgb(206, 206, 206)';
            items[i].style.color='black';
        }
        Toast.info('抽题成功！', 1);
    };
    selectItem=(itemIdx,rightAnswer,currentTotal)=>{
        console.log('当前被点击的是：',itemIdx,rightAnswer);
        let items = document.getElementsByClassName('item');
        if(itemIdx==rightAnswer){
            console.log('回答正确');
            this.setState({
                selectRightNum:this.state.selectRightNum+1,
                integral:this.state.integral+10
            })
            items[itemIdx-1].style.backgroundColor='green';
            items[itemIdx-1].style.color='white';
        }else{
            console.log('回答错误');
            this.setState({
                selectWrongNum:this.state.selectWrongNum+1
            })
            items[itemIdx-1].style.backgroundColor='red';
            items[itemIdx-1].style.color='white';
            items[rightAnswer-1].style.backgroundColor='green';
            items[rightAnswer-1].style.color='white';
        }
        let that =this;
        setTimeout(function () { 
            if(that.state.countNum<currentTotal-1){
                that.setState({
                    countNum:that.state.countNum+1
                });
                
           for(let i=0;i<items.length;i++){
                items[i].style.backgroundColor='rgb(206, 206, 206)';
                items[i].style.color='black';
            }
                
            }else{
                Toast.info('没有题目啦！3秒后进行结算！', 5);
                let data ={
                    selectRightNum:that.state.selectRightNum,
                    integral:that.state.integral,
                    selectWrongNum:that.state.selectWrongNum
                }
                that.props.addSettlementData(data);
                console.log('结算：',that.state);
                setTimeout(function () { 
                     that.props.history.push('/Settlement')
                 },3000)
               
            }
         },300)

    };
    render(){
        // console.log('DatiCom 中的props=>',this.props);
        let listData = this.props.TopicData?this.props.TopicData.data.result:null;
        //进行分页处理，一页10个题目
        let pagesObj = {};
        let tempArr =[];
        if(Array.isArray(listData) && listData){
           listData.forEach((item,idx)=>{
               let num = idx; 
                if(num % 10 === 9 && num !==0){
                    // console.log(num,item);
                    tempArr.push(item);
                    // console.log(tempArr);
                    pagesObj[(idx.toString()==='9'?'09':idx.toString()).substr(0,1)] =tempArr;
                    tempArr =[];
                }else{
                    tempArr.push(item); 
                }       
            }); 
            console.log('分页处理后的数据：',pagesObj);
        }
        if(!listData){
            Toast.info('加载中!', 1);
            return (
                <div className='DatiCompre' style={{'backgroundColor':'gray'}}></div>
            )
        }else{
            let randomNum = this.state.randomNum;
            let countNum =this.state.countNum;
            // console.log('数据：',pagesObj[randomNum])
            let timuTotal = pagesObj[randomNum].length;
            // console.log('randomNum是：',randomNum,countNum);
            return (
                <div className='DatiCom' >
                    <header>
                        <span className='goBackBtn' onClick={()=>this.changeTopic(-1,timuTotal)}> 上一题</span>
                        <h4>随机答题</h4>
                        <span className='nextBtn' onClick={()=>this.changeTopic(1,timuTotal)}>下一题</span>
                    </header>
                    <div className='topic_body'>
                        <div className='topicDes'>
                            <div className='imgWrap'>
                                <img src={pagesObj[randomNum][countNum]?pagesObj[randomNum][countNum].url:''}></img>
                            </div>
                            <div className='title'>
                              题目{this.state.countNum+1}：{pagesObj[randomNum][countNum].question}                              
                            </div>

                        </div>
                        <div className='item_options'>
                            {
                                console.log(pagesObj[randomNum][countNum])
                            }
                            <span className='item' onClick={()=>this.selectItem(1,pagesObj[randomNum][countNum].answer,timuTotal)}>1.{pagesObj[randomNum][countNum].item1?pagesObj[randomNum][countNum].item1:'-'}</span>
                            <span className='item' onClick={()=>this.selectItem(2,pagesObj[randomNum][countNum].answer,timuTotal)}>2.{pagesObj[randomNum][countNum].item2?pagesObj[randomNum][countNum].item2:'-'}</span>
                            <span className='item' onClick={()=>this.selectItem(3,pagesObj[randomNum][countNum].answer,timuTotal)}>3.{pagesObj[randomNum][countNum].item3?pagesObj[randomNum][countNum].item3:'-'}</span>
                            <span className='item' onClick={()=>this.selectItem(4,pagesObj[randomNum][countNum].answer,timuTotal)}>4.{pagesObj[randomNum][countNum].item4?pagesObj[randomNum][countNum].item4:'-'}</span>
                        </div>
                    </div>
                    <Button onClick={this.resetTopic} style={{position:'fixed',bottom:'0',width:'100%',fontSize:'1rem'}}>重新抽题</Button>
                </div>
            )
        }
        
    }
};

const DatiCom =connect(
    mapStateToProps,
    mapDispatchToprops
  )(Dati1)
export default DatiCom